import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse

# 设置谷歌浏览器的请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 - monitor"
}
# 设置手机标头
mobilePhoneUserAgent = {
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 - monitor"
}
# 2024.5.14 检测正常页面的时间
defaultTime = "2024.5.14"

#需要检测的网址与md5值 （md5值第一次获取后填写）
toBeTestArr = [
    {"url": "网站1", "md5": "第一次需要手动填写"},
    {"url": "网站2", "md5": "第一次需要手动填写"},
]
#需要手机标头访问的
mobileStation = [
    "网站1"
]

#钉钉相关配置
secret = " "  #密匙
access_token = " " #链接里面的

def timingDetection():
    changeContent = ''
    for ix in toBeTestArr:
        if ix['url'] in mobileStation:
            print(ix['url'])
            response = requests.get(ix['url'], headers=mobilePhoneUserAgent)
        else:
            response = requests.get(ix['url'], headers=headers)
        content = response.content.decode('utf8')
        soup = str(content)
        soup = soup[:1800]  # 截取前1800字符
        md = hashlib.md5(soup.encode())
        mdx = md.hexdigest()
        if mdx != ix['md5']:
            changeContent += "网站：【" + ix['url'] + "】\n"
        print(ix['url'], mdx)
    if changeContent:
        changeContent += "以上网站页面内容与" + defaultTime + "检测的内容不一致，请手动判断是否被篡改。"
        sendMessage(changeContent)
    else:
        print("检测未发生篡改")

def sendMessage(content):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    ddUrl = "https://oapi.dingtalk.com/robot/send?access_token=" + access_token + "×tamp=" + timestamp + "&sign=" + sign
    data = {
        'at':
            {
                'atUserIds': [],
                'atMobiles': [],
                'isAtAll': True,
            },
        'text': {
            'content': content
        },
        'msgtype': 'text',
    }
    headers['Content-Type'] = 'application/json'
    r = requests.post(url=ddUrl, data=json.dumps(data), headers=headers)
    w = json.loads(r.text)
    print(w)

if __name__ == '__main__':
    timingDetection()